<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*,java.nio.file.*" %>
<%@ page import="javax.servlet.http.Cookie" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%
//检查登录
Cookie[] cookies = request.getCookies();
String logonusername = null;
if (cookies != null) {
    for (Cookie cookie : cookies) {
        if ("logonusername".equals(cookie.getName())) {
        	logonusername = cookie.getValue(); // 获取Cookie的值
            break; 
        }
    }
}
request.setAttribute("logonusername", logonusername);
%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<link rel="stylesheet" href="style/css/index.css" />
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>留言管理系统 - 首页</title>
</head>
<body>
<div id="app">
<div class="main">
<div class="top">
<%
	if(logonusername!=null) {
		out.println("<a class='user'>"+logonusername+"</a>");
		out.println("<h1>留言板首页</h1>");
		out.println("<a class='user' href='api/exit.jsp'>退出登录</a>");
	}else{
		out.println("<a class='user' href='logon.jsp'>登录</a>");
		out.println("<h1>留言板首页</h1>");
	}
	%>
	</div>
	<div class="main-all">
<%
    Connection conn = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/message", "message", "message");
        stmt = conn.createStatement();
        // 执行SQL查询
        String sql = "SELECT id,name,msg,time FROM mess order by id LIMIT 15"; 
        rs = stmt.executeQuery(sql);
	 	// 遍历
        while (rs.next()) {
        	int mid = rs.getInt("id");
          	String name = rs.getString("name");
          	String msg = rs.getString("msg");
          	String time = rs.getString("time");
%>
    <div class="msg">
		<b><%=name %></b>
		<p><%=msg %></p>
		<sup><%=time %></sup>
		<%  if(name.equals(logonusername)){
			out.println("<button onclick=\"window.location.href='api/def.jsp?mid="+mid+"'\">删除</button>");
		}
		%>
	</div>
<%
        }
    } catch (Exception e) {
          e.printStackTrace(); // 打印异常
    } finally {
            // 关闭资源
            try { if (rs != null) rs.close(); } catch (SQLException e) { /* ignored */ }
            try { if (stmt != null) stmt.close(); } catch (SQLException e) { /* ignored */ }
            try { if (conn != null) conn.close(); } catch (SQLException e) { /* ignored */ }
        }
%>
		<form action="api/put.jsp" method="post">
			<div class="input">
				<input type="text" name="messmsg" placeholder="留言内容"  required>
				<input type="submit" value="提交" />
			</div>
		</form>
	</div>
</div>
</div>
	
</body>
</html>